#!/usr/env/bin python
# -*- coding: utf-8 -*-

# @Time    : 2018/10/16 11:58
# @Author  : yangdy
# @Email   : yangdy@egu360.com
# @File    : email.py
# @Software: PyCharm
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
from email.mime.image import MIMEImage
from email.mime.audio import MIMEAudio
from email.header import Header


class Email:

    def __init__(self, host, port, t=''):
        if t.lower() == 'ssl':
            self.smtp = smtplib.SMTP_SSL(host=host, port=port)
        else:
            self.smtp = smtplib.SMTP(host=host, port=port)
            self.smtp.ehlo()
            self.smtp.starttls()
        self.msg_root = MIMEMultipart('related')
        self.msg_al = MIMEMultipart('alternative')
        self.msg_root.attach(self.msg_al)

    def login(self, user, password):
        self.smtp.login(user=user, password=password)

    def attachment(self, file):
        mime = MIMEApplication(file.read())
        mime.add_header('Content-Disposition', 'attachment', filename=file.name)
        self.msg_root.attach(mime)

    def image(self, image, imageId):
        mime = MIMEImage(image.read())
        mime.add_header('Content-ID', imageId)
        self.msg_root.attach(mime)

    def sendmail(self, from_address, receivers, subject, message):
        self.msg_root['Subject'] = Header(subject, 'utf-8').encode()
        self.msg_root['From'] = from_address
        self.msg_root['To'] = ';'.join(receivers)
        mime = MIMEText(message, 'html', 'utf-8')
        self.msg_al.attach(mime)
        self.smtp.sendmail(from_address, receivers, self.msg_root.as_string())


def main():
    smtp_server = 'smtp.exmail.qq.com'
    smtp_port = 465
    from_addr = 'yangdy@egu360.com'
    password = 'GkR7yP4T4o8j4wvs'

    receivers = ['137740537@qq.com', 'caott@egu360.com',
                 # 'wenjing@egu360.com', 'liangpp@egu360.com',
                 # 'fanss@egu360.com'
                 ]
    # receivers = ['137740537@qq.com', ]
    email = Email(smtp_server, smtp_port, 'ssl')
    email.login(from_addr, password)
    with open('test.jpg', 'rb') as f:
        email.attachment(f)
    with open('test1.png', 'rb') as f:
        email.image(f, '<image1>')
    subject = "hello"
    message = """
        <h1>hello</h1>
        <img src="cid:image1" width=200>
        <a href="http://egu360.com">egu360</a>
    """
    email.sendmail(from_addr, receivers, subject, message)


if __name__ == '__main__':
    main()
